package com.ayitubie.refuelweb.controller;

import com.alibaba.fastjson.JSON;
import com.ayitubie.refuelweb.config.crypto.CryptoUtil;
import com.ayitubie.refuelweb.config.jedis.JedisService;
import com.ayitubie.refuelweb.entity.GasStation;
import com.ayitubie.refuelweb.entity.HttpClientRes;
import com.ayitubie.refuelweb.minio.MinioTemplate;
import com.ayitubie.refuelweb.service.GasStationServ;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.jsoup.nodes.Element;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/station")
public class GasStationCtl {

    @Autowired
    private GasStationServ gasStationServ;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    RedissonClient redissonClient;


    @Autowired
    JedisService jedisService;

    @Autowired
    CryptoUtil cryptoUtil;

    @Cacheable(cacheNames = "station", sync = true)
    @GetMapping("/query/all")
    public List<GasStation> getAllStations() {
        log.info("查询所有加油站");
        return gasStationServ.getAllStation();
    }

    /**
     * HTTP client 调用远程接口，获取本周限号
     *
     * @return
     */
    @GetMapping("/query/all/limit")
    public List getAllLimitFromBjgov() {
        RLock lock = redissonClient.getLock("limit-lock");
        lock.lock();
        List list = new ArrayList();
        try {
            String limit = jedisService.get("limit");
            if (StringUtils.isNotEmpty(limit)) {
                log.info("限行：从redis读 [{}]", limit);
                list = JSON.parseObject(limit, List.class);
                // 读不到，直接调接口
            } else {
                String url = "http://yw.jtgl.beijing.gov.cn/jgjxx/services/getRuleWithWeek";
                HttpClientRes res = restTemplate.getForObject(url, HttpClientRes.class);
                if (res != null) {
                    list = res.getResult();
                    jedisService.setEx("limit", JSON.toJSONString(list), 10 * 60);
                } else {
                    list = null;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return list;
    }

    public static void main(String[] args) {
        try {
            HashMap<String, String> map = new LinkedHashMap<>();
            String url = "https://www.so.com/s?q=%E5%8C%97%E4%BA%AC%E9%99%90%E8%A1%8C";
            Document doc = Jsoup.connect(url).get();
            Elements number = doc.select("table.g-table tbody td");

            System.out.println(number);
            LocalDate today = LocalDate.now();
            LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
            List<LocalDate> weekDates = new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                weekDates.add(startOfWeek.plusDays(i));
            }
            for (int i = 0; i < weekDates.size(); i++) {
                map.put(weekDates.get(i).toString(), number.get(i).html());
            }
            System.out.println(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/query/all/baidu/limit")
    public HashMap<String, String> getAllLimitFromBaidu() {
        RLock lock = redissonClient.getLock("limit-lock");
        lock.lock();
        HashMap<String, String> map = new LinkedHashMap<>();
        try {
            String limit = jedisService.get("limit");
            if (StringUtils.isNotEmpty(limit)) {
                log.info("限行：从redis读 [{}]", limit);
                map = JSON.parseObject(limit, LinkedHashMap.class);
                // 读不到，直接调接口
            } else {
                String url = "https://www.so.com/s?q=%E5%8C%97%E4%BA%AC%E9%99%90%E8%A1%8C";
                Document doc = Jsoup.connect(url).get();
                Elements number = doc.select("table.g-table tbody td");
                System.out.println(number);
                LocalDate today = LocalDate.now();
                LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                List<LocalDate> weekDates = new ArrayList<>();
                for (int i = 0; i < 7; i++) {
                    weekDates.add(startOfWeek.plusDays(i));
                }
                for (int i = 0; i < weekDates.size(); i++) {
                    map.put(weekDates.get(i).toString(), number.get(i).html());
                }
                jedisService.setEx("limit", JSON.toJSONString(map), 8 * 60 * 60);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return map;
    }

    @GetMapping("/minio/getUrl")
    public String getUrl(@RequestParam(required = false, defaultValue = "") String bucketName, @RequestParam(required = false, defaultValue = "") String objectName, @RequestParam(required = false, defaultValue = "0") int expires) {
        return minioTemplate.getObjectURL(bucketName, objectName, expires);
        //return minioTemplate.getObjectURL(bucketName, cryptoUtil.desEncrypt(objectName), expires);
    }
}
